package com.lxj.easyadapter;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.utils.PlainArray;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class ViewHolder {

    private final PlainArray<Component> mViews;
    @NotNull
    private final Component convertView;

    private int adapterPosition = -1;

    @NotNull
    public final Component getView(int viewId) {
        Component view = mViews.get(viewId).orElse(null);
        if (view == null) {
            view = convertView.findComponentById(viewId);
            mViews.put(viewId, view);
        }

        return view;
    }

    @Nullable
    public final Component getViewOrNull(int viewId) {
        Component view = mViews.get(viewId).orElse(null);
        if (view == null) {
            view = this.convertView.findComponentById(viewId);
            mViews.put(viewId, view);
        }

        return view;
    }

    @NotNull
    public final ViewHolder setText(int viewId, @NotNull String text) {
        Text tv = (Text) getView(viewId);
        if (tv != null) {
            tv.setText(text);
        }

        return this;
    }

    @NotNull
    public final ViewHolder setImageResource(int viewId, int resId) {
        Image view = (Image) getView(viewId);
        if (view != null) {
            view.setImageElement(ResUtil.getPixelMapDrawable(view.getContext(), resId));
        }

        return this;
    }

    @NotNull
    public final Component getConvertView() {
        return this.convertView;
    }

    public ViewHolder(@NotNull Component convertView) {
        this.convertView = convertView;
        this.mViews = new PlainArray<>();
    }

    @NotNull
    public static ViewHolder createViewHolder(@NotNull Component itemView) {
        return new ViewHolder(itemView);
    }

    @NotNull
    public static ViewHolder createViewHolder(@NotNull Context context, @NotNull ComponentContainer parent, int layoutId) {
        Component itemView = LayoutScatter.getInstance(context).parse(layoutId, parent, false);
        return new ViewHolder(itemView);
    }

    public int getAdapterPosition() {
        return adapterPosition;
    }

    public void setAdapterPosition(int adapterPosition) {
        this.adapterPosition = adapterPosition;
    }
}
